package com.cnpinxi.controller.web.order;

import com.cnpinxi.controller.base.BaseController;
import com.cnpinxi.def.Constant;
import com.cnpinxi.domain.AdminUser;
import com.cnpinxi.domain.Order;
import com.cnpinxi.domain.User;
import com.cnpinxi.myRunTime.MyRunTimeExcption;
import com.cnpinxi.result.ResultObj;
import com.cnpinxi.service.OrderItemService;
import com.cnpinxi.service.OrderService;
import com.cnpinxi.service.RefundService;
import com.cnpinxi.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

//import com.github.pagehelper.PageHelper;
//import com.github.pagehelper.PageInfo;

/**
 * Created by baggio on 2016/12/27.
 */
@RequestMapping("/order")
@Controller
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;


    @Autowired
    private RefundService refundService;


    @RequestMapping(value = "/orderList")
    public ModelAndView orderList(HttpServletRequest request, HttpServletResponse response) {        // source: 1(来源于网站) | 2(来源于微站)
        ModelAndView mov = new ModelAndView();
        mov.setViewName("/web/order/orderList");
        if (super.getIsMobile(request)) {
            mov.setViewName("/wap/order/orderList");
            super.oauth2(request, response);
            HttpSession session = request.getSession();
            try {
                String openId = (String) session.getAttribute(Constant.SESSION_OPEN_ID);
                if (StringUtils.isNotBlank(openId)) {
                    User user = super.getUserByOpenId(openId);
                    session.setAttribute(Constant.SESSION_KEY_USER_LOGIN, user);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mov;
    }

    @RequestMapping(value = "/createOrder")
    @ResponseBody
    public String createOrder(HttpServletRequest request) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {
            Map<String, String> map = this.showRequestParameters(request);

            Order order = orderService.createOrder(map, super.getUserBySession(request));
            resultObj.setData(order);
        } catch (MyRunTimeExcption runTimeExcption) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(runTimeExcption.getMessage());
            runTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }
        logger.info("resultObj==>" + resultObj.toJson());
        return resultObj.toJson();
    }

    @RequestMapping(value = "/getOrderPriceAmount")
    @ResponseBody
    public String getOrderPriceAmount(HttpServletRequest request) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {
            Map<String, String> map = this.showRequestParameters(request);

            String startDate = DateUtil.dateToStr(DateUtil.getWeekStartDate(), DateUtil.DATE);
            String endDate = DateUtil.dateToStr(DateUtil.addDay(DateUtil.getWeekStartDate(), 7), DateUtil.DATE);
            map.put("startDate", startDate);
            map.put("endDate", endDate);
            Integer orderPriceAmount = orderService.getOrderPricAmount(map);
            resultObj.setData(orderPriceAmount);
        } catch (MyRunTimeExcption runTimeExcption) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(runTimeExcption.getMessage());
            runTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }
        logger.info("resultObj==>" + resultObj.toJson());
        return resultObj.toJson();
    }


    @RequestMapping(value = "/cancelOrderItem", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public String cancelOrderItem(HttpServletRequest request, Long orderItemId) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {
            orderItemService.cancelOrderItem(orderItemId);
        } catch (MyRunTimeExcption runTimeExcption) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(runTimeExcption.getMessage());
            runTimeExcption.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultObj.toJson();
    }

    @RequestMapping(value = "/cancelOrder")
    @ResponseBody
    public String cancelOrder(Long orderId) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {
            orderService.cancelOrder(orderId);
        } catch (MyRunTimeExcption runTimeExcption) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(runTimeExcption.getMessage());
            runTimeExcption.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultObj.toJson();
    }


    @RequestMapping(value = "/getOrderById")
    @ResponseBody
    public String getOrderById(HttpServletRequest request, Long orderId) {
        logger.info("【getOrderById===>】" + orderId);
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {
            Order order = orderService.getOrderById(orderId);
            resultObj.setData(order);

        } catch (Exception e) {
            resultObj.setCode(ResultObj.CODE_FAIL);
        }
        logger.info("resultObj.toJson()===>>>>" + resultObj.toJson());
        return resultObj.toJson();
    }

    @RequestMapping(value = "/getOrderList", method = RequestMethod.POST)
    @ResponseBody
    public String getOrderList(HttpServletRequest request, Integer page, Integer pageSize) {
        logger.info("【getOrderList】");
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        Map<String, String> map = this.showRequestParameters(request);
        try {
            if (page == null || page == 0) {
                page = Constant.PAGENUM;
            }
            // 设置每页记录数
            if (pageSize == null || pageSize == 0) {
                pageSize = Constant.PAGESIZENum;
            }
            PageHelper.startPage(page, pageSize);
            AdminUser adminUser = (AdminUser) request.getSession().getAttribute(Constant.SESSION_KEY_ADMDIN_USER_LOGIN);
            if (adminUser == null) {
                String userId = map.get("userId");
                logger.info("user====>>>>" + userId);
                if (StringUtils.isBlank(userId)) {
                    throw new MyRunTimeExcption("用户未登录！");
                }

            }

            List<Order> orderList = orderService.getOrderList(map);
            PageInfo<Order> pageinfo = new PageInfo<Order>(orderList);
            resultObj.setData(pageinfo);

        } catch (MyRunTimeExcption runTimeExcption) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(runTimeExcption.getMessage());
            runTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return resultObj.toJson();
    }


    @RequestMapping(value = "/refund")
    @ResponseBody
    public String refund(Long orderId, String refundReason) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {
            if (!refundService.refund(orderId, refundReason)) {
                resultObj.setCode(ResultObj.CODE_FAIL);
                resultObj.setMsg("申请退款失败！");
            }
        } catch (MyRunTimeExcption runTimeExcption) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(runTimeExcption.getMessage());
            runTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return resultObj.toJson();
    }

    @RequestMapping(value = "/cancelRefund")
    @ResponseBody
    public String cancelRefund(Long orderId) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {
            if (!refundService.cancelRefund(orderId)) {
                resultObj.setCode(ResultObj.CODE_FAIL);
                resultObj.setMsg("退款失败！");
            }
        } catch (MyRunTimeExcption runTimeExcption) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(runTimeExcption.getMessage());
            runTimeExcption.printStackTrace();
        } catch (Exception e) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return resultObj.toJson();
    }


    @RequestMapping(value = "/orderConfirm")
    @ResponseBody
    public String orderConfirm(Long orderId) {
        ResultObj resultObj = new ResultObj();
        resultObj.setCode(ResultObj.CODE_SUCCESS);
        try {

            if (!orderService.completeOrder(orderId)) {
                resultObj.setCode(ResultObj.CODE_FAIL);
                resultObj.setMsg("确认支付失败！");
            }

        } catch (MyRunTimeExcption runTimeExcption) {
            resultObj.setCode(ResultObj.CODE_FAIL);
            resultObj.setMsg(runTimeExcption.getMessage());
            runTimeExcption.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultObj.toJson();
    }


}
